package org.practice.intercepter;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.practice.action.BaseAction;
import org.practice.model.User;
import org.practice.util.Constant;
import org.practice.util.CookieUtil;
import org.practice.util.IAnonymous;
import org.practice.util.ShopServiceFactory;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

/**
 * 校验是否登录，未登录的用户不可执行action，除非action实现了IAnonymous匿名接口
 * 拦截购物车action，购物需要先登陆，验证seesion是否失效，如果失效就返回一个提示视图
 * @author jack
 */
@SuppressWarnings("serial")
public class LoginInterceptor implements Interceptor{
	
	public void destroy() {
	}
	public void init() {
		
	}
	public String intercept(ActionInvocation invocation) throws Exception {
		BaseAction baseAction = (BaseAction)invocation.getAction();
		HttpServletRequest request=ServletActionContext.getRequest();
		
		boolean isLogin = false;
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute(Constant.SESSION_KEY_USER);
		if (user != null) {
			isLogin = true;
		} else {
			String uid = CookieUtil.findCookie(request, Constant.COOKIE_KEY_USERID);
			if (uid != null) {
				user = ShopServiceFactory.createUserService().findUserById(Integer.parseInt(uid));
				if (user != null) {
					session.setAttribute(Constant.SESSION_KEY_USER, user);
					isLogin = true;
				}
			}
		}
		//每次购物操作之前都要判断该用户是否已经登录过，并且购物车相关的action是否实现匿名接口
        if (!(baseAction instanceof IAnonymous)&&!isLogin) {
            return Constant.SESSION_TIMEOUT;
        }else{
        	return invocation.invoke();
        }
	}
 
}